from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func, or_
from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.models.knowledge_base import KnowledgeBase
from app.models.document import Document
from app.schemas.knowledge_base import (
    KnowledgeBaseCreate,
    KnowledgeBaseUpdate,
    KnowledgeBaseResponse,
    KnowledgeBaseListResponse
)
import logging
import uuid

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/knowledge-bases", tags=["knowledge-bases"])


@router.get("/list", response_model=KnowledgeBaseListResponse)
async def list_knowledge_bases(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取知识库列表（用户自己的 + 共享的）
    """
    try:
        # 获取用户可见的知识库
        knowledge_bases = db.query(KnowledgeBase).filter(
            or_(
                KnowledgeBase.owner_id == str(current_user.id),
                KnowledgeBase.visibility == 'PUBLIC',
                KnowledgeBase.visibility == 'DEPARTMENT'
            )
        ).order_by(KnowledgeBase.created_at.desc()).all()
        
        # 统计文档数量
        doc_counts = db.query(
            Document.knowledge_base_id,
            func.count(Document.id).label('count')
        ).filter(
            Document.knowledge_base_id.isnot(None)
        ).group_by(Document.knowledge_base_id).all()
        
        doc_count_map = {kb_id: count for kb_id, count in doc_counts}
        
        items = []
        for kb in knowledge_bases:
            items.append({
                "id": kb.id,
                "name": kb.name,
                "description": kb.description,
                "visibility": kb.visibility.value.lower() if kb.visibility else 'private',
                "owner_id": kb.owner_id,
                "owner_name": kb.owner_name,
                "document_count": doc_count_map.get(kb.id, 0),
                "created_at": kb.created_at,
                "updated_at": kb.updated_at
            })
        
        return {
            "items": items,
            "total": len(items)
        }
        
    except Exception as e:
        logger.error(f"获取知识库列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取知识库列表失败: {str(e)}")


@router.post("/create", response_model=KnowledgeBaseResponse)
async def create_knowledge_base(
    kb: KnowledgeBaseCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建知识库"""
    try:
        # 检查名称是否已存在
        existing = db.query(KnowledgeBase).filter(
            KnowledgeBase.name == kb.name,
            KnowledgeBase.owner_id == str(current_user.id)
        ).first()
        
        if existing:
            raise HTTPException(status_code=400, detail="知识库名称已存在")
        
        # 转换visibility为枚举值
        from app.models.knowledge_base import KnowledgeBaseVisibility
        visibility_map = {
            'private': KnowledgeBaseVisibility.PRIVATE,
            'public': KnowledgeBaseVisibility.PUBLIC,
            'shared': KnowledgeBaseVisibility.DEPARTMENT,
            'department': KnowledgeBaseVisibility.DEPARTMENT,
        }
        visibility_enum = visibility_map.get(kb.visibility.lower(), KnowledgeBaseVisibility.PRIVATE)
        
        # 创建知识库
        new_kb = KnowledgeBase(
            id=str(uuid.uuid4()),
            name=kb.name,
            description=kb.description,
            visibility=visibility_enum,
            owner_id=str(current_user.id),
            owner_name=current_user.username
        )
        
        db.add(new_kb)
        db.commit()
        db.refresh(new_kb)
        
        logger.info(f"用户 {current_user.username} 创建知识库: {new_kb.name}")
        
        return {
            "id": new_kb.id,
            "name": new_kb.name,
            "description": new_kb.description,
            "visibility": new_kb.visibility.value.lower() if new_kb.visibility else 'private',
            "owner_id": new_kb.owner_id,
            "owner_name": new_kb.owner_name,
            "document_count": 0,
            "created_at": new_kb.created_at,
            "updated_at": new_kb.updated_at
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建知识库失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建失败: {str(e)}")


@router.put("/{kb_id}", response_model=KnowledgeBaseResponse)
async def update_knowledge_base(
    kb_id: str,
    kb_update: KnowledgeBaseUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新知识库"""
    kb = db.query(KnowledgeBase).filter(KnowledgeBase.id == kb_id).first()
    
    if not kb:
        raise HTTPException(status_code=404, detail="知识库不存在")
    
    if kb.owner_id != str(current_user.id):
        raise HTTPException(status_code=403, detail="无权限修改此知识库")
    
    try:
        from app.models.knowledge_base import KnowledgeBaseVisibility
        visibility_map = {
            'private': KnowledgeBaseVisibility.PRIVATE,
            'public': KnowledgeBaseVisibility.PUBLIC,
            'shared': KnowledgeBaseVisibility.DEPARTMENT,
            'department': KnowledgeBaseVisibility.DEPARTMENT,
        }
        
        if kb_update.name is not None:
            kb.name = kb_update.name
        if kb_update.description is not None:
            kb.description = kb_update.description
        if kb_update.visibility is not None:
            kb.visibility = visibility_map.get(kb_update.visibility.lower(), KnowledgeBaseVisibility.PRIVATE)
        
        db.commit()
        db.refresh(kb)
        
        # 统计文档数量
        doc_count = db.query(func.count(Document.id)).filter(
            Document.knowledge_base_id == kb_id
        ).scalar() or 0
        
        return {
            "id": kb.id,
            "name": kb.name,
            "description": kb.description,
            "visibility": kb.visibility.value.lower() if kb.visibility else 'private',
            "owner_id": kb.owner_id,
            "owner_name": kb.owner_name,
            "document_count": doc_count,
            "created_at": kb.created_at,
            "updated_at": kb.updated_at
        }
        
    except Exception as e:
        logger.error(f"更新知识库失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新失败: {str(e)}")


@router.delete("/{kb_id}")
async def delete_knowledge_base(
    kb_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除知识库"""
    kb = db.query(KnowledgeBase).filter(KnowledgeBase.id == kb_id).first()
    
    if not kb:
        raise HTTPException(status_code=404, detail="知识库不存在")
    
    if kb.owner_id != str(current_user.id):
        raise HTTPException(status_code=403, detail="无权限删除此知识库")
    
    try:
        # 检查是否有文档
        doc_count = db.query(func.count(Document.id)).filter(
            Document.knowledge_base_id == kb_id
        ).scalar()
        
        if doc_count > 0:
            raise HTTPException(status_code=400, detail=f"该知识库下还有{doc_count}个文档，无法删除")
        
        db.delete(kb)
        db.commit()
        
        logger.info(f"用户 {current_user.username} 删除知识库: {kb.name}")
        
        return {"message": "删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除知识库失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")

